/*
 * Copyright [2010] [GP Software]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * JdbcDao.java | Created on April 27, 2010
 */
package org.gp.gpetl.dao.impl;

import org.gp.gpetl.config.BeanMapping;
import org.gp.gpetl.dao.AbstractJdbcDao;
import org.gp.gpetl.dao.Dao;
import org.gp.gpetl.exception.DaoException;
import org.gp.gpetl.util.SqlQueryWrapper;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;

import java.util.List;

/**
 * Implementation of JDBC data access
 *
 * @author Paul Augustine C. Mendoza
 * @since 1.0
 */
public class JdbcDao extends AbstractJdbcDao implements Dao {

    /**
     * @see org.gp.gpetl.dao.Dao#insert(org.gp.gpetl.config.BeanMapping,
     *      java.util.List)
     */
    public int insert(BeanMapping beanMapping, List<String[]> records) throws
            DaoException {
        if (records == null) {
            throw new IllegalArgumentException("Records cannot be null.");
        }
        int cnt = 0;
        if (records.size() > 1) {
            SqlQueryWrapper queryVo = new SqlQueryWrapper(beanMapping, records);
            for (String[] row : queryVo.getData()) {
                try {
                    cnt += getJdbcTemplate().update(queryVo.getInsertSql(),
                            queryVo.getParameters(row));
                } catch (DuplicateKeyException dke) {
                    System.out.println(dke.getMessage());
                } catch (DataAccessException dae) {
                    throw new DaoException(dae, row);
                }
            }
        }
        return cnt;
    }
}
